package com.application.magazine;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.magazine.bookitem.BooksAdapter;
import com.application.magazine.bookitem.BookshelfView;
import com.devspark.appmsg.AppMsg;
import com.roscopeco.ormdroid.Entity;
import com.roscopeco.ormdroid.ORMDroidApplication;

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity {
	private FrameLayout fBookStand,frame_content_book_mybook;
	private ImageView bookStandBtn,book_book_download;
	private TextView textView1,book_download;
	private int cur;
	private int last;
	private Activity activity;
	private BookshelfView bsView;
	private ViewPager pager;
	private MagazineBookPane mAdapter;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ORMDroidApplication.initialize(MainActivity.this);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		setContentView(R.layout.main_layout);
		bsView = (BookshelfView) findViewById(R.id.bookShelfGrid);
		bookStandBtn = (ImageView) findViewById(R.id.bookStandBtn);
		book_book_download = (ImageView) findViewById(R.id.book_book_download);
		fBookStand = (FrameLayout) findViewById(R.id.frame_content_book_stand);
		frame_content_book_mybook = (FrameLayout) findViewById(R.id.frame_content_book_mybook);
		frame_content_book_mybook.setVisibility(View.INVISIBLE);
		textView1 = (TextView) findViewById(R.id.dlStatus);
		book_download = (TextView) findViewById(R.id.textView2);
		LayoutInflater inflater = this.getLayoutInflater();
		activity = MainActivity.this;
		View pagerView = inflater.inflate(R.layout.book_stand_list, fBookStand);
		pager =  (ViewPager) pagerView.findViewById(R.id.pager_book_inside);
		mAdapter = new MagazineBookPane(getSupportFragmentManager());
		pager.setAdapter(mAdapter);
		
		pager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				cur = arg0;
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		bookStandBtn.setImageDrawable(getResources().getDrawable(R.drawable.books_selected));
		textView1.setTextColor(Color.parseColor(GlobalVariable.BLUE_COLOR));
		book_book_download.setImageDrawable(getResources().getDrawable(R.drawable.mybook));
		book_download.setTextColor(Color.parseColor(GlobalVariable.BLACK_COLOR));
		
		bookStandBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MagazineBookPane mAdapter = new MagazineBookPane(getSupportFragmentManager());
				pager.setAdapter(mAdapter);
				bookStandBtn.setImageDrawable(getResources().getDrawable(R.drawable.books_selected));
				textView1.setTextColor(Color.parseColor(GlobalVariable.BLUE_COLOR));
				
				book_book_download.setImageDrawable(getResources().getDrawable(R.drawable.mybook));
				book_download.setTextColor(Color.parseColor(GlobalVariable.BLACK_COLOR));
				frame_content_book_mybook.setVisibility(View.INVISIBLE);
				fBookStand.setVisibility(View.VISIBLE);
			}
		});
		book_book_download.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				(new DownloadBooksTask(getApplicationContext(), bsView, MainActivity.this)).execute();
				
				bookStandBtn.setImageDrawable(getResources().getDrawable(R.drawable.books));
				textView1.setTextColor(Color.parseColor(GlobalVariable.BLACK_COLOR));
				
				book_book_download.setImageDrawable(getResources().getDrawable(R.drawable.mybook_selected));
				book_download.setTextColor(Color.parseColor(GlobalVariable.BLUE_COLOR));
				frame_content_book_mybook.setVisibility(View.VISIBLE);
				fBookStand.setVisibility(View.INVISIBLE);
			}
		});
	}
	
	public ViewPager getPager() {
		return pager;
	}
	public void setPager(ViewPager pager) {
		this.pager = pager;
	}
	public MagazineBookPane getmAdapter() {
		return mAdapter;
	}
	public void setmAdapter(MagazineBookPane mAdapter) {
		this.mAdapter = mAdapter;
	}
	public void refresh(){
		mAdapter.notifyDataSetChanged();
	}

	class MagazineBookPane extends FragmentPagerAdapter {

		private List<Item_Magazine> magList;
		

		public MagazineBookPane(FragmentManager fragmentManager) {
			super(fragmentManager);
		}

		@Override
		public Fragment getItem(int position) {			
			return BookListFragment.newInstance(getMagList(), cur, getCount(), activity);
		}


		@Override
		public int getCount() {
			return getMagList().size()>0 ? getMagList().size()/4 : 1;
		}

		public List<Item_Magazine> getMagList() {
				if(magList==null || last!=cur){
					last = cur;
					magList = new ArrayList<Item_Magazine>();
					JSONParserForGetList json = new JSONParserForGetList();
					List<Item_Magazine> mList = json.getMagazineAll();
					if(mList!=null && mList.size()>0){
							int c = cur!=0?cur*4:0;
							for(int i=0;i<4;i++){
								if(mList.size()>(c+1)){
								magList.add(mList.get(c+i));
								}
							}
						
					}
				}
			return magList;
		}

		public void setMagList(List<Item_Magazine> magList) {
			this.magList = magList;
		}
		
	
		
		
	}
	public class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {

        private int currentPage;

        @Override
        public void onPageSelected(int position) {
            currentPage = position;
            cur = currentPage;
        }

        public final int getCurrentPage() {
            return currentPage;
        }
    }
	class DownloadBooksTask extends AsyncTask<String, Void, List<Magazine>> {
		ProgressDialog pDialog;
		private Context context;
		private BookshelfView view;
		public Activity send;

		public DownloadBooksTask(Context context, BookshelfView view,
				Activity aa) {
			super();
			this.context = context;
			this.view = view;
			this.send = aa;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage(GlobalVariable.LOADING_DIALOG_MESSAGE);
			pDialog.show();
		}

		@Override
		protected List<Magazine> doInBackground(String... params) {

			InputStream is = null;
			List<Magazine> listTest = Entity.query(Magazine.class)
					.executeMulti();
			Collections.sort(listTest,Collections.reverseOrder(new ComparableMagazine()));
			return listTest;
		}

		@Override
		protected void onPostExecute(List<Magazine> result) {
			super.onPostExecute(result);
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}

			if (result != null) {
				view.setAdapter(new BooksAdapter(context, result, send));
			} else {
				
			}

		}

	}
//	private void buildInterface() {
//		// set the Content View
//		setContentView(R.layout.frame_content);
//
//		// set the Behind View
//		setBehindContentView(R.layout.frame_menu);
//
//		initRightFragments();
//
//		initLeftFragments();
//	}
//
//	private void buildSlingMenu() {
//		// customize the SlidingMenu
//		SlidingMenu sm = getSlidingMenu();
//		sm.setMode(SlidingMenu.LEFT);
//		sm.setShadowWidthRes(R.dimen.shadow_width);
//		sm.setShadowDrawable(R.drawable.drawer_menu_shadow);
//		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
//		DisplayMetrics dm = new DisplayMetrics();
//		MainActivity.this.getWindowManager().getDefaultDisplay().getMetrics(dm);
//		int width = dm.widthPixels;
//		System.out.println(width);
//		sm.setFadeDegree(0.35f);
//		sm.setBehindWidth((60*width)/100);
//		sm.setBehindScrollScale(0.25f);
//	}
//
//	private void initLeftFragments() {
//		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//		
//		fragmentTransaction.replace(R.id.menu, getLeftMenuFragment(),LeftMenuFragment.class.getName());
//		
//		fragmentTransaction.commit();
//	}
//
//	private void initRightFragments() {
//		PhotoFragment photo = getPhotoFragment();
//
//		FragmentTransaction fragmentTransaction = getSupportFragmentManager()
//				.beginTransaction();
//
//		if (!photo.isAdded()) {
//			fragmentTransaction.add(R.id.content, photo,
//					PhotoFragment.class.getName());
//			fragmentTransaction.hide(photo);
//		}
//
//		if (!fragmentTransaction.isEmpty()) {
//			fragmentTransaction.commit();
//			getSupportFragmentManager().executePendingTransactions();
//		}
//	}
//
//	public LeftMenuFragment getLeftMenuFragment() {
//		LeftMenuFragment fragment = ((LeftMenuFragment) getSupportFragmentManager()
//				.findFragmentByTag(LeftMenuFragment.class.getName()));
//		if (fragment == null) {
//			fragment = new LeftMenuFragment();
//		}
//		return fragment;
//	}
//
//	public PhotoFragment getPhotoFragment() {
//		PhotoFragment fragment = ((PhotoFragment) getSupportFragmentManager().findFragmentByTag(PhotoFragment.class.getName()));
//		if (fragment == null) {
//			fragment = new PhotoFragment();
//		}
//		return fragment;
//	}
//
//	public NoticeFragment getNoticeFragment() {
//		NoticeFragment fragment = ((NoticeFragment) getSupportFragmentManager().findFragmentByTag(NoticeFragment.class.getName()));
//		if (fragment == null) {
//			fragment = new NoticeFragment();
//		}
//		return fragment;
//	}
//
//	public SetFragment getSetFragment() {
//		SetFragment fragment = ((SetFragment) getSupportFragmentManager()
//				.findFragmentByTag(SetFragment.class.getName()));
//		if (fragment == null) {
//			fragment = new SetFragment();
//		}
//		return fragment;
//	}


}